package com.study.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.junit.Test;
/*
当两个线程同时通过lock.lockInterruptibly()想获取某个锁时，假若此时线程A获取到了锁，而线程B只有等待，那么对线程B调用threadB.interrupt()方法能够中断线程B的等待过程。

【注意是：等待的那个线程B可以被中断，不是正在执行的A线程被中断】
 */
public class lockInterruptiblyTest {

	@Test
	public void testlockInterruptibly() throws InterruptedException{
		BussinessClass bussinessClass = new BussinessClass();
		
		Thread t0 = new Thread(){
			@Override
			public void run(){
				bussinessClass.bFunction();
			}
		};
		
		Thread t1 = new Thread(){
			@Override
			public void run(){
				bussinessClass.bFunction();
			}
		};
		
		String tName = Thread.currentThread().getName();
		System.out.println(tName + "启动t0..");
		t0.start();
		System.out.println(tName + "等我个5s, 我再启动个t1..");
		Thread.sleep(5000);
		System.out.println(tName + "启动t1..");
		t1.start();
		
		System.out.println(tName + "-t1获取不到锁，t0这货睡觉了, 没释放，我等个5s.");
		Thread.sleep(5000);
		System.out.println(tName + "等了个5秒, 不等了, 把t1中断掉.");
		t1.interrupt();
		
		Thread.sleep(Long.MAX_VALUE);
	}
}

class BussinessClass{
	private Lock lock = new ReentrantLock();
	public void bFunction(){
		String name = Thread.currentThread().getName();
		try{
			System.out.println(name + "-开始获取锁..");
			lock.lockInterruptibly();
			System.out.println(name + "-获取到锁了.");
			System.out.println(name + "-睡觉, 睡个15秒.");
			
			Thread.sleep(15000);
			System.out.println(name + "-睡醒了, 干活.");
			
			for(int i = 0; i < 5; i++){
				System.out.println(name + " " + i);
			}
			
		}catch (Exception e) {
			System.out.println(name + "-好像被中断了.");
			e.printStackTrace();
		}finally { 
			lock.unlock();
			System.out.println(name + "-释放了锁。。");
		}
	}
}